import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/user'

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    token: '',
    userInfo: {},
    isLogin: false
  }),
  getters: {
    userId: (state) => state.userInfo.id || '',
    userName: (state) => state.userInfo.nickname || '',
    userAvatar: (state) => state.userInfo.avatarUrl || '/static/default-avatar.png'
  },
  actions: {
    // 登录
    async login(loginForm) {
      try {
        const res = await login(loginForm)
        this.token = res.token
        this.isLogin = true
        
        // 获取用户信息
        await this.getUserInfo()
        
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const res = await getUserInfo()
        this.userInfo = res
        return res
      } catch (error) {
        throw error
      }
    },
    
    // 退出登录
    async logout() {
      try {
        await logout()
        this.resetUserInfo()
      } catch (error) {
        this.resetUserInfo()
        throw error
      }
    },
    
    // 重置用户信息
    resetUserInfo() {
      this.token = ''
      this.userInfo = {}
      this.isLogin = false
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user-store',
        storage: {
          getItem: (key) => uni.getStorageSync(key),
          setItem: (key, value) => uni.setStorageSync(key, value)
        }
      }
    ]
  }
})    